package com.qigao.erp.web.controller;

import com.qigao.erp.commons.FileInfoService;
import com.qigao.erp.commons.dto.FileResultDto;
import com.qigao.erp.commons.enums.FileTypeEnum;
import com.qigao.erp.commons.enums.Result;
import com.qigao.erp.commons.enums.ResultCode;
import com.qigao.erp.jdbc.model.TbFileInfo;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author luiz
 * @Title: FileController
 * @ProjectName s3
 * @Description: 文件存储公共服务
 * @date 2019-04-02 14:10
 * 版本1：
 * 1)提供文件查询功能,根据文件编号,返回文件流
 */
@Controller
@RequestMapping("/common/file")
@Api(tags = "Common文件相关")
public class FileController {
    private static final Logger logger= LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileInfoService fileInfoService;

    @Value("${share.file.path:/}")
    private String shareFilePath;

    @ResponseBody
    @PostMapping("/uploadFile")
    public Result<FileResultDto> uploadFile(@RequestParam("file") MultipartFile multipartFile)  {
        if(multipartFile==null)return Result.newError(ResultCode.COMMON_PARAM_NULL.getCode(),"文件不能为空");
        try {

            String originFileName=multipartFile.getOriginalFilename();
            long fileSize=multipartFile.getSize()/1024;//转成KB
            logger.info("文件名:{}文件大小:{}",originFileName,fileSize);
            return  fileInfoService.saveFile(multipartFile);
        } catch (Exception e) {
            logger.error("[文件存储]文件上传发生异常!{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    /**
     * 按照文件编号输出文件流
     */
    @GetMapping("/findByNo/{fileNo}")
    private void findByNo(@PathVariable("fileNo") String fileNo, HttpServletResponse response){
        try {
            TbFileInfo tbFileInfo= fileInfoService.findByFileNo(fileNo);
            String fileType="NONE";
            String fileName="NONE";
            byte[] fileBytes=null;
            if(tbFileInfo!=null){
                String fileInfoFileNo=tbFileInfo.getFileNo();
                if(fileNo.equals(tbFileInfo.getZipFileNo())){
                    fileInfoFileNo=tbFileInfo.getZipFileNo();
                }else if(fileNo.equals(tbFileInfo.getNarrowFileNo())){
                    fileInfoFileNo=tbFileInfo.getNarrowFileNo();
                }
                String realPath=tbFileInfo.getFileUrl()+fileInfoFileNo+"."+tbFileInfo.getFileType();
                File file=new  File(realPath);
                fileName=file.getName();
                fileType=fileName.split("\\.")[1];
                InputStream fis=new FileInputStream(file);
                if(fis!=null){
                    ByteArrayOutputStream bos= new ByteArrayOutputStream(1024);
                    byte[] b = new byte[1024];
                    int n;
                    while ((n = fis.read(b)) != -1) {
                        bos.write(b, 0, n);
                    }
                    fis.close();
                    bos.close();
                    fileBytes = bos.toByteArray();
                }
            }
            if(fileBytes==null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            if(FileTypeEnum.ifImage(fileType)){
                response.setContentType(FileTypeEnum.getContentTypeByType(fileType));
            }else {
                //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
                response.setContentType("multipart/form-data");
                //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
                response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            }
            // 响应输出流
            ServletOutputStream out = response.getOutputStream();
            // 创建缓冲区
            int bufferLen=1024;
            int fileSize=fileBytes.length;
            for(int i=0;i<=fileSize/bufferLen-1;i++){
                int startIndex=i*bufferLen;
                if(i==fileSize/bufferLen){
                    int remainLen=fileSize % bufferLen;
                    out.write(fileBytes, startIndex, remainLen);
                }else {
                    out.write(fileBytes, startIndex, bufferLen);
                }
            }
            // out.write(fileBytes);
            out.flush();
            out.close();
        }  catch (IOException e) {
            logger.error("[文件存储]文件编号:{}输出文件流异常!{}",shareFilePath,e);
        }
    }
}
